package com.example.remoteassistance;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.litepal.LitePal;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLEncoder;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

//注册活动
public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "RegisterActivity";

    private EditText mUsername;
    private EditText mPassword;
    private EditText mPasswordAgain;
    private Button mSure;
    private Button mCancel;

    private Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        //导航栏返回按钮
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setTitle("返回");
            actionBar.setDisplayHomeAsUpEnabled(true);
        }

        initViews();
    }

    //导航栏返回按钮点击事件
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            //返回注册界面
            startActivity(new Intent(this, LoginActivity.class));
            this.finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    //初始化界面
    private void initViews() {
        mContext = getApplicationContext();
        mUsername = (EditText) findViewById(R.id.et_register_username);
        mPassword = (EditText) findViewById(R.id.et_register_password);
        mPasswordAgain = (EditText) findViewById(R.id.et_register_password_again);
        mSure = (Button) findViewById(R.id.bt_register_sure);
        mCancel = (Button) findViewById(R.id.bt_register_cancel);
        mSure.setOnClickListener(this);
        mCancel.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            //注册按钮点击
            case R.id.bt_register_sure:
                register();
                break;
            //注册取消
            case R.id.bt_register_cancel:
                startActivity(new Intent(this, LoginActivity.class));
                finish();
                break;
        }
    }

    //注册信息输入是否规范
    private boolean isRegisterEditValid(String username, String password, String passwordAgain) {
        if (username.equals("")) {
            Toast.makeText(this, "用户名不能为空", Toast.LENGTH_SHORT).show();
            return false;
        } else if (password.equals("") || passwordAgain.equals("")) {
            Toast.makeText(this, "密码不能为空", Toast.LENGTH_SHORT).show();
            return false;
        } else if (!password.equals(passwordAgain)) {
            Toast.makeText(this, "密码不一致", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    //注册
    private void register() {
        String url = URLUtils.HTTPURL + "register";
        String username = mUsername.getText().toString().trim();
        String password = mPassword.getText().toString().trim();
        String passwordAgain = mPasswordAgain.getText().toString().trim();

        //判断信息输入是否规范
        if (isRegisterEditValid(username,password, passwordAgain)) {
            //密码MD5加密
            String passwordMD5 = MD5Utils.getMD5(password);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        String data = "username=" + URLEncoder.encode(username, "UTF-8")
                                + "&password=" + URLEncoder.encode(passwordMD5, "UTF-8");

                        //HTTP POST数据
                        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
                        conn.setRequestMethod("POST");
                        conn.setReadTimeout(3000);
                        conn.setConnectTimeout(3000);
                        conn.setUseCaches(false);

                        OutputStream out = conn.getOutputStream();
                        out.write(data.getBytes());
                        out.flush();
                        out.close();

                        //判断应答码
                        if (conn.getResponseCode() == 200) {
                            InputStream in = conn.getInputStream();
                            ByteArrayOutputStream msg = new ByteArrayOutputStream();
                            int len = 0;
                            byte buf[] = new byte[1024];
                            while ((len = in.read(buf)) != -1) {
                                msg.write(buf, 0, len);
                            }
                            in.close();
                            msg.close();

                            //判断注册状态
                            String registerType = msg.toString();
                            switch (registerType) {
                                //注册成功
                                case "SUCCESS":
                                    SPUtils.put(mContext, "username", username);
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            //跳转回登录界面
                                            startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
                                            Toast.makeText(RegisterActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
                                            finish();
                                        }
                                    });
                                    break;
                                //注册失败
                                case "FAIL":
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(RegisterActivity.this, "注册失败", Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                    break;
                                //用户已注册
                                case "REGISTERED":
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(RegisterActivity.this, "用户已注册", Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                    break;
                            }
                        }
                    } catch (SocketTimeoutException e) {
                        e.printStackTrace();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(RegisterActivity.this, "服务器连接超时", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }  catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }
}